﻿using Microsoft.AspNetCore.Mvc;

namespace Huasky.Rest.Controllers;

/// <summary>
/// 学生
/// </summary>
[ApiController]
[Route("[controller]")]
public class StudentController(IHttpContextAccessor httpContextAccessor, ILogger<StudentController> logger)
{
    private static int Num = 1;
    private HttpContext _httpContext = httpContextAccessor.HttpContext;
    private readonly ILogger<StudentController> logger = logger;

    [HttpPost("[action]")]
    public Student Create(Student stu)
    {
        using var db = new MainDbContext();
        stu.Id = Num++;
        db.Students.Add(stu);
        db.SaveChanges();
        return stu;
    }

    [HttpGet("[action]")]
    public List<Student> List()
    {
        using var db = new MainDbContext();
        return db.Students?.ToList() ?? [];
    }


    [HttpGet("[action]/{id}")]
    public Student Get(int id)
    {
        var header = _httpContext.Request.Headers["Authentication"].SingleOrDefault();
        if (string.IsNullOrEmpty(header))
        {
            logger.LogError("未认证");
            _httpContext.Response.StatusCode = 401;
            return null;
        }
        if (header.ToString() != "sunxiaoshuangzaiwuhan")
        {
            logger.LogError("授权失败");
            _httpContext.Response.StatusCode = 403;
            return null;
        }
        using var db = new MainDbContext();
        return db.Students.FirstOrDefault(a => a.Id == id);
    }
}
